<template>
  <div>
    <!--页面区域-->
    <div class="page-view">

      <!--搜索条件表单-->
      <div class="table-operations">
        <a-space>
          <a-form ref="queryForm" :model="data.queryParam" layout="inline">  
            <a-form-item label="角色编码">  
              <a-input v-model:value="data.queryParam.roleCode" placeholder="请输入角色编码" />  
            </a-form-item>  
            <a-form-item label="角色名称">  
              <a-input v-model:value="data.queryParam.roleName" placeholder="请输入角色名称" />  
            </a-form-item>  
            <a-button type="primary" @click="onSearch">搜索</a-button> 
            <a-button type="primary" @click="onReset">重置</a-button> 
          </a-form> 
        </a-space> 
      </div>  


      <div class="table-operations">
        <a-space>
          <a-button type="primary" @click="handleAdd">新增</a-button>
          <a-button @click="handleBatchDelete">批量删除</a-button>
        </a-space>
      </div>

      <!-- table 列表-->
      <a-table size="middle" rowKey="id" :loading="data.loading" :columns="columns" :data-source="data.dataList"
        @change="getRoleList" :scroll="{ x: 'max-content' }" :row-selection="rowSelection" :pagination="pagination">
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'dataStatus'">
            <span>
              <span v-if="text === 1"><a-tag color="success">启用</a-tag></span>
              <span v-if="text === 0"><a-tag color="error">禁用</a-tag></span>
            </span>
          </template>
          <template v-if="column.key === 'operation'">
            <span>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="handleEditRoleResource(record)">权限配置</a>
              <a-divider type="vertical" />
              <a @click="handleShowRoleUser(record)">用户列表</a>
              <a-divider type="vertical" />
              <a-divider type="vertical" />
              <a-popconfirm title="确定删除?" ok-text="是" cancel-text="否" @confirm="confirmDelete(record)">
                <a href="#">删除</a>
              </a-popconfirm>
            </span>
          </template>
        </template>
      </a-table>
    </div>

    <!--弹窗区域-->
    <!--新增/编辑 角色的弹窗-->
    <div>
      <a-modal :visible="modal.visile" :forceRender="true" :title="modal.title" ok-text="确认" cancel-text="取消"
        @cancel="handleCancel" @ok="handleOk">
        <div>
          <a-form ref="myform" :label-col="{ style: { width: '80px' } }" :model="modal.form" :rules="modal.rules">
            <a-row :gutter="24">
              <a-col span="24">
                <a-form-item label="角色编码" name="roleCode">
                  <a-input  :disabled="modal.editFlag" placeholder="请输入" v-model:value="modal.form.roleCode"
                    allowClear />
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="角色名称" name="roleName">
                 <a-input placeholder="请输入" v-model:value="modal.form.roleName" allowClear />
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="状态" name="dataStatus">
                  <a-switch checked-children="启" un-checked-children="禁" v-model:checked="modal.form.dataStatusChecked" />
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="备注" name="remark">
                  <a-textarea
                    v-model:value="modal.form.remark"
                    placeholder="请输入"
                    :auto-size="{ minRows: 2, maxRows: 5 }"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </a-modal>
    </div>

    <!--新增/编辑 角色配置资源权限的弹窗-->
    <div>
      <a-modal :visible="modal.visileResource" :forceRender="true" title="角色配置资源"  width="80%"
        ok-text="确认" cancel-text="取消"
        @cancel="handleResourceCancel" @ok="handleResourceOk">
        <div>
          <!--系统资源树形结构的table-->
          <a-table :columns="resourceColumns" :data-source="treeData.dataList" 
                   :row-selection="{ selectedRowKeys: treeData.selectedResourceKeys, onChange: onSelectChangeResource}" >
            <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'type'">
                  <span>
                    <span v-if="text === 1">菜单</span>
                    <span v-if="text === 2">按钮</span>
                    <span v-if="text === 3">功能</span>
                  </span>
                </template>
                <template v-if="column.key === 'dataStatus'">
                  <span>
                    <span v-if="text === 1"><a-tag color="success">启用</a-tag></span>
                    <span v-if="text === 0"><a-tag color="error">禁用</a-tag></span>
                  </span>
                </template>
                
              </template>
          </a-table>
        </div>
      </a-modal>
    </div>


    <!--角色绑定用户列表的弹窗-->
    <div>
      <a-modal :visible="modal.visileRoleRelUser" :forceRender="true" title="角色关联用户列表"  width="80%"
        ok-text="确认" cancel-text="取消"
        @cancel="hideRoleUserModal" @ok="handleResourceOk">
        <div>
          <div class="table-operations">
            <a-space>
              <a-button type="primary" @click="handleRoleAddUserModal">新增</a-button>
              <a-button @click="handleRoleUserDelete">批量删除</a-button>
            </a-space>
          </div>
          <a-table :columns="roleRelUserTableColumns" :data-source="roleRelUserData.dataList" :loading="roleRelUserData.loading" 
              :row-selection="roleRelUserRowSelection" >
            <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'type'">
                  <span>
                    <span v-if="text === 1">菜单</span>
                    <span v-if="text === 2">按钮</span>
                    <span v-if="text === 3">功能</span>
                  </span>
                </template>
                <template v-if="column.key === 'dataStatus'">
                  <span>
                    <span v-if="text === 1"><a-tag color="success">启用</a-tag></span>
                    <span v-if="text === 0"><a-tag color="error">禁用</a-tag></span>
                  </span>
                </template>
                
              </template>
          </a-table>
        </div>
      </a-modal>
    </div>


    <!--用于被选择的用户列表的弹窗-->
    <div>
      <a-modal :visible="modal.visileActiveUser" :forceRender="true" title="用户列表"  width="80%"
        ok-text="确认" cancel-text="取消"
        @cancel="hideRoleAddUserModal" @ok="handleResourceOk">
        <div>
          <a-table :columns="roleRelUserTableColumns" :data-source="userActiveData.dataList" :loading="userActiveData.loading" 
              :row-selection="roleRelUserRowSelection" :pagination="userActicePagination" @change="getSelectUserList">
            <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'type'">
                  <span>
                    <span v-if="text === 1">菜单</span>
                    <span v-if="text === 2">按钮</span>
                    <span v-if="text === 3">功能</span>
                  </span>
                </template>
                <template v-if="column.key === 'dataStatus'">
                  <span>
                    <span v-if="text === 1"><a-tag color="success">启用</a-tag></span>
                    <span v-if="text === 0"><a-tag color="error">禁用</a-tag></span>
                  </span>
                </template>
                
              </template>
          </a-table>
        </div>
      </a-modal>
    </div>



  </div>
</template>

<script setup lang="ts">
import { FormInstance, message } from 'ant-design-vue';
import { queryRoleListApi, createApi, updateApi, deleteApi, bindingResourceApi, bindingResourceDetailsApi, queryRelUsersApi } from '/@/api/role';
import {  queryMenuTreeDataApi } from '/@/api/resource';
import {  userListApi } from '/@/api/user';
import { getFormatTime } from "/@/utils";



 // 控制角色列表显示的字段
const columns = reactive([
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center',
  },
  {
    title: '角色编码',
    dataIndex: 'roleCode',
    key: 'roleCode',
    align: 'center',
  },
  {
    title: '角色名称',
    dataIndex: 'roleName',
    key: 'roleName',
    align: 'center',
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'dataStatus',
    key: 'dataStatus',
    align: 'center',
    customRender: ({ text, record, index, column }) => (text === 1 ? '正常' : '禁用'),
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    customRender: ({ text }) => getFormatTime(text, true)
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'operation',
    align: 'center',
    fixed: 'right',
  },
]);

// 控制配置系统资源列表显示的字段
const resourceColumns = reactive([
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center',
  },
   {
    title: '资源类型',
    dataIndex: 'type',
    key: 'type',
    align: 'center',
  },
   {
    title: '资源编码',
    dataIndex: 'code',
    key: 'code',
    align: 'center',
  },
  {
    title: '资源名称',
    dataIndex: 'name',
    key: 'name',
    align: 'center',
  },
   {
    title: '资源路径',
    dataIndex: 'resUrl',
    key: 'resUrl',
    align: 'center',
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'dataStatus',
    key: 'dataStatus',
    align: 'center',
    customRender: ({ text, record, index, column }) => (text === 1 ? '正常' : '禁用'),
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    customRender: ({ text }) => getFormatTime(text, true)
  }
]);

// 角色关联的用户列表table显示的列
const roleRelUserTableColumns = reactive([
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center',
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
    align: 'center',
  },
  {
    title: '昵称',
    dataIndex: 'nickname',
    key: 'nickname',
    align: 'center',
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
    align: 'center',
  },
  {
    title: '手机号',
    dataIndex: 'mobile',
    key: 'mobile',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'dataStatus',
    key: 'dataStatus',
    align: 'center',
  },
  
]);



// 角色页面数据
const data = reactive({
  dataList: [],
  queryParam: {
    keyword: '',
    pageSize: 10,
    page: 1,
    total: 0,
    roleCode: '',
    roleName: '',
  },
  loading: false,
  selectedRowKeys: [] as any[],
});

// 角色列表分页
const pagination = computed(() => ({
  size: 'default',
  current: data.queryParam.page,
  pageSize: data.queryParam.pageSize,
  total: data.queryParam.total,
  onChange: (current) => (data.queryParam.page = current),
  showSizeChanger: false,
  showTotal: (total) => `共${total}条数据`,
}));

// 系统资源数据
const treeData = reactive({
  dataList: [],
  // 勾选系统资源的资源ID集合
  selectedResourceKeys: [] as any[],
  // 当前配置的角色ID
  selectedRoleId: undefined,
});

// 角色关联用户列表数据
const roleRelUserData = reactive({
  dataList: [],
  queryParam: {
    pageSize: 10,
    page: 1,
    total: 0,
    roleId: undefined,
  },
  loading: false,
  selectedRowKeys: [] as any[],
});

// 用于选择的用户列表数据
const userActiveData = reactive({
  dataList: [],
  queryParam: {
    pageSize: 10,
    page: 1,
    total: 0,
  },
  loading: false,
  selectedRowKeys: [] as any[],
});

// 用于选择的用户列表数据的列表分页
const userActicePagination = computed(() => ({
  size: 'default',
  current: userActiveData.queryParam.page,
  pageSize: userActiveData.queryParam.pageSize,
  total: userActiveData.queryParam.total,
  onChange: (current) => ( userActiveData.queryParam.page = current  ),
  showSizeChanger: false,
  showTotal: (total) => `共${total}条数据`,
}));


// 弹窗数据源
const modal = reactive({
  //角色数据弹窗相关变量
  visile: false,
  editFlag: false,
  title: '',
  //角色配置资源的弹窗相关变量
  visileResource: false,
  //角色绑定用户列表的弹窗相关变量
  visileRoleRelUser: false,
  //角色添加用户的列表弹窗的变量
  visileActiveUser: false,
  form: {
    id: undefined,
    roleCode: undefined,
    roleName: undefined,
    dataStatus: undefined,
    remark: undefined,
    dataStatusChecked: true,
  },
  rules: {
    roleCode: [{ required: true, message: '请输入', trigger: 'change' }],
    roleName: [{ required: false, message: '请输入', trigger: 'change' }],
    remark: [{ required: false, message: '请选择', trigger: 'change' }]
  },
});

const myform = ref<FormInstance>();

const roleResourceform = ref<FormInstance>();

onMounted(() => {
  getRoleList();
});

// 列表查询
const getRoleList = () => {
  data.loading = true;
  queryRoleListApi(data.queryParam)
    .then((res) => {
      data.loading = false;
      data.dataList = res.content.records;
      data.queryParam.total = res.content.total;
      data.dataList.forEach((item: any, index: any) => {
        item.index = index + 1;
      });
    })
    .catch((err) => {
      data.loading = false;
      console.log(err);
    });
};


// 搜索按钮调用列表查询接口
const onSearch = () => {
  getRoleList();
};

// 重置搜索条件
const onReset = () => {
  data.queryParam.roleCode = '';
  data.queryParam.roleName = '';
  getRoleList();
};

const rowSelection = ref({
  onChange: (selectedRowKeys: (string | number)[], selectedRows: DataItem[]) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    data.selectedRowKeys = selectedRowKeys;
    console.log(data.selectedRowKeys);
  },
});


// 系统资源勾选change的触发方法
const onSelectChangeResource = (selectedRowKeys: Key[]) => {
  console.log('selectedResourceKeys changed: ', selectedRowKeys);
  treeData.selectedResourceKeys = selectedRowKeys;
};

// 系统资源table的勾选的触发方法
const rowSelectionResource = ref({
  onChange: (selectedRowKeys: (string | number)[], selectedRows: DataItem[]) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },
  onSelect: (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
    console.log(record, selected, selectedRows);
  },
  onSelectAll: (selected: boolean, selectedRows: DataItem[], changeRows: DataItem[]) => {
    console.log(selected, selectedRows, changeRows);
  },
});

// 角色关联用户列表的勾选
const roleRelUserRowSelection = ref({
  onChange: (selectedRowKeys: (string | number)[], selectedRows: DataItem[]) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    roleRelUserData.selectedRowKeys = selectedRowKeys;
    console.log(roleRelUserData.selectedRowKeys);
  },
});

// 新增的方法
const handleAdd = () => {
  resetModal();
  modal.visile = true;
  modal.editFlag = false;
  modal.title = '新增';
  // 重置
  for (const key in modal.form) {
    modal.form[key] = undefined;
  }
  modal.form.dataStatusChecked = true;
};

// 编辑的方法
const handleEdit = (record: any) => {
  resetModal();
  modal.visile = true;
  modal.editFlag = true;
  modal.title = '编辑';
  // 重置
  for (const key in modal.form) {
    modal.form[key] = undefined;
  }
  for (const key in record) {
    modal.form[key] = record[key];
  }
  if(modal.form.dataStatus === 1){
    modal.form.dataStatusChecked = true;
  }
};

// 删除的方法
const confirmDelete = (record: any) => {
  console.log('delete', record);
  deleteApi({ ids: record.id })
    .then((res) => {
      message.success('删除成功');
      getRoleList();
    })
    .catch((err) => {
      message.error(err.response.data.message || "操作失败")
    });
};

// 批量删除的方法
const handleBatchDelete = () => {
  console.log(data.selectedRowKeys);
  if (data.selectedRowKeys.length <= 0) {
    console.log('hello');
    message.warn('请勾选删除项');
    return;
  }
  deleteApi({ ids: data.selectedRowKeys.join(',') })
    .then((res) => {
      message.success('删除成功');
      data.selectedRowKeys = [];
      getRoleList();
    })
    .catch((err) => {
      message.error(err.response.data.message || "操作失败")
    });
};

// 二次确认 点击ok的方法
const handleOk = () => {
  myform.value
    ?.validate()
    .then(() => {
      const formData = new FormData();
      if (modal.form.id) {
        formData.append('id', modal.form.id);
      }
      if (modal.form.roleCode) {
        formData.append('roleCode', modal.form.roleCode);
      }
      if (modal.form.roleName) {
        formData.append('roleName', modal.form.roleName);
      }
      if (modal.form.remark) {
        formData.append('remark', modal.form.remark);
      }
      if (modal.form.dataStatusChecked && modal.form.dataStatusChecked === true) {
        formData.append('dataStatus', 1);
      } else {
        formData.append('dataStatus', 0);
      }
      if (modal.editFlag) {
        updateApi(formData)
          .then((res) => {
            message.success('修改成功');
            hideModal();
            getRoleList();
          })
          .catch((err) => {
            console.log(err);
            message.error(err.response.data.message || "操作失败")
          });
      } else {
        createApi(formData)
          .then((res) => {
            message.success('添加成功');
            hideModal();
            getRoleList();
          })
          .catch((err) => {
            console.log(err);
            message.error(err.response.data.message || "操作失败")
          });
      }
    })
    .catch((err) => {
      console.log('不能为空');
    });
};

// 角色配置资源的二次确认 点击ok的方法
const handleResourceOk = () => {
    console.log('handleResourceOk');
    const formData = new FormData();
    formData.append('roleId', treeData.selectedRoleId);
    console.log(treeData.selectedResourceKeys);
    treeData.selectedResourceKeys.forEach((value, index) => {  
      formData.append(`resourceIds[${index}]`, value);  
    });
    bindingResourceApi(formData)
      .then((res) => {
        message.success('添加成功');
        hideResourceModal();
        getRoleList();
      })
      .catch((err) => {
        console.log(err);
        message.error(err.response.data.message || "操作失败")
      });
    treeData.selectedRoleId = undefined;
    treeData.selectedResourceKeys = [];
};

// 二次确认点击取消的方法
const handleCancel = () => {
  hideModal();
};

const handleResourceCancel = () => {
  hideResourceModal();
};

// 恢复表单初始状态
const resetModal = () => {
  myform.value?.resetFields();
};

// 关闭弹窗
const hideModal = () => {
  modal.visile = false;
};

const hideResourceModal = () => {
  modal.visileResource = false;
  treeData.selectedResourceKeys = [];
};

// 点击【权限配置】触发的方法
const handleEditRoleResource = (record: any) => {
  resetModal();
  modal.visileResource = true;
  getMenuTreeData();
  getRoleResourceDetail(record.id);
  // 当前要配置的角色ID
  treeData.selectedRoleId = record.id;
  
};

// 树形结构的菜单列表查询
const getMenuTreeData = () => {
  data.loading = true;
  queryMenuTreeDataApi(data.queryParam)
    .then((res) => {
      data.loading = false;
      treeData.dataList = res.content;
      treeData.dataList.forEach((item: any, index: any) => {
        item.index = index + 1;
      });
      console.log('getMenuTreeData 数据');
      console.log(res.content);
    })
    .catch((err) => {
      data.loading = false;
      console.log(err);
    });
};

// 单个角色查看绑定的资源列表的接口
const getRoleResourceDetail = (roleId: number) => {
  bindingResourceDetailsApi(roleId)
    .then((res) => {
      treeData.selectedResourceKeys = res.content;
    })
    .catch((err) => {
      console.log(err);
    });
};

// 角色查看关联的用户列表的接口
const getRelUsersList = () => {
  roleRelUserData.loading = true;
  queryRelUsersApi(roleRelUserData.queryParam)
    .then((res) => {
      roleRelUserData.loading = false;
      roleRelUserData.dataList = res.content.records;
      roleRelUserData.queryParam.total = res.content.total;
      roleRelUserData.dataList.forEach((item: any, index: any) => {
        item.index = index + 1;
      });
    })
    .catch((err) => {
      roleRelUserData.loading = false;
      console.log(err);
    });
};

// 点击【用户列表】的触发方法
const handleShowRoleUser = (record: any) => {

  modal.visileRoleRelUser = true;
  roleRelUserData.queryParam.roleId = record.id;
  getRelUsersList();
  
};

// 隐藏角色关联用户的弹窗
const hideRoleUserModal = () => {
  modal.visileRoleRelUser = false;
};


// 显示用户列表
const handleRoleAddUserModal = () => {
  modal.visileActiveUser = true;
  getSelectUserList();
};

// 隐藏用户列表
const hideRoleAddUserModal = () => {
  modal.visileActiveUser = false;
};


// 用户列表查询api
const getSelectUserList = () => {
  userActiveData.loading = true;
  userListApi(data.queryParam)
    .then((res) => {
      userActiveData.loading = false;
      userActiveData.dataList = res.content.records;
      userActiveData.queryParam.total = res.content.total;
      userActiveData.dataList.forEach((item: any, index: any) => {
        item.index = index + 1;
      });
    })
    .catch((err) => {
      userActiveData.loading = false;
      console.log(err);
    });
};

// 批量移除角色关联的用户
const handleRoleUserDelete = () => {
};

</script>

<style scoped lang="less">
.page-view {
  min-height: 100%;
  background: #fff;
  padding: 24px;
  display: flex;
  flex-direction: column;
}

.table-operations {
  margin-bottom: 16px;
  text-align: right;
}

.table-operations>button {
  margin-right: 8px;
}

// 以下class名称是组件生成的，查看页面元素才知道
.ant-form> button {
  margin-right: 8px;
}

</style>
